import { Actions, } from 'react-native-router-flux';
import { Tabs, Toast, Portal } from '@ant-design/react-native';

import axios from 'axios';
import store from '../store/store';
import request from './request'
import { removeData, saveData } from '../util/utils';

import * as ActionTypes from '../constants/constants.js';

axios.defaults.baseURL = 'http://e-trader.io/v1/app';

const api = {
  async get(url, data) {
    return await axios.get(url, {
      headers: {
        'Content-Type': 'application/json',
      },
      params: {
        ...data,
      }
    });
  },
  async post(url, data) {
    return await axios({
      url,
      data,
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      }
    });
  },
  async upload(url, data) {
    console.log(data)
    return await axios({
      url,
      data,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },
};

axios.interceptors.request.use((request) => {
  let token = store.getState().token
  if (token) {
    request.headers["token"] = token
  }
  console.log(request)
  return request;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});



axios.interceptors.response.use((response) => {
  console.log(response)
  if (response.data.code == 401) {
    // token 失效了
    // console.log('登录失效了')
    return request.refreshToken().then(token => {
      console.log(token, '刷新token')
      if (token.data) {
        const config = response.config
        store.dispatch({
          type: ActionTypes.setToken,
          data: token.data.token
        })
        // console.log('刷新token')
        Actions.mall()
        return axios(config)
      }
    }).catch(res => {
      // console.log('refreshtoken error =>', res)
      //刷新token失败，神仙也救不了了，跳转到首页重新登录吧
      // window.location.href = '/'
      Toast.fail('登录失效', 1)
      store.dispatch({
        type: ActionTypes.clearToken
      })
      Actions.login()
    })
  }
  return response;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

export default api;
